<?php

namespace app\modules\controllers;
use Yii;
use app\models\Category;
use yii\helpers\ArrayHelper;
class CategoryController extends \yii\web\Controller
{
    /**
     * [actionList 版块列表]
     *
     * @DateTime 2017-12-09
     *
     * @return   [type]
     */
    public function actionList()
    {
        $this->layout='layout1';
        $model=new Category;
        $cates=$model->getTreeList();
        return $this->render('list',['cates'=>$cates]);
    }

    /**
     * [actionAdd 添加版块]
     *
     * @DateTime 2017-12-09
     *
     * @return   [type]
     */
    public function actionAdd()
    {
        $this->layout='layout1';
        $model=new Category;
        // 创建层级分类
        $list=$model->getOptions();

        // var_dump($list);die;
        if(Yii::$app->request->isPost)
        {
            $post=Yii::$app->request->post();
            if($model->add($post))
            {
                Yii::$app->session->setFlash('info','添加成功');
            }
        }
        return $this->render('add',['list'=>$list,'model'=>$model]);
    }

    /**
     * [actionMod 编辑分类]
     *
     * @DateTime 2017-12-11
     *
     * @return   [type]
     */
    public function actionMod()
    {
        // 修改的操作是根据传递过来cateid ,修改parentid 和 title
        $this->layout='layout1';
        $cateid=Yii::$app->request->get('cateid');
        $model=Category::find()->where('cateid=:id',[':id'=>$cateid])->one();
        // 判断提交修改
        if(Yii::$app->request->isPost)
        {
            $post=Yii::$app->request->post();
            if($model->load($post) && $model->save())
            {
                Yii::$app->session->setFlash('info','操作成功');
            }
        }   
        $list=$model->getOptions();

        return $this->render('add',['model'=>$model,'list'=>$list]);
    }
    /**
     * [actionDel 执行删除操作]
     *
     * @DateTime 2017-12-11
     *
     * @return   [type]
     */
    public function actionDel()
    {
        try {
            $cateid=Yii::$app->request->get('cateid');
            // 没有传递过来真实ID
            if(empty($cateid))
            {
                throw new \Exception('参数错误');
            }

            $data=Category::find()->where('parentid=:pid',[':pid'=>$cateid])->one();
            // 查询是否有子类
            if($data)
            {
                throw new \Exception('该分类下有子类!');
            }
            // 
            if(!Category::deleteAll('cateid=:id',[':id'=>$cateid]))
            {
                throw new \Exception('删除失败');
            }
        } catch (\Exception $e) {   
            Yii::$app->session->setFlash('info',$e->getMessage());
        }

        return $this->redirect(['category/list']);
    }



}
